<template>


    <el-button type="primary" @click="ManageCreate(null)">新增</el-button>
    <el-button type="primary" @click="DelManage(arreryDel)">批量删除</el-button>
    <el-button type="success" @click="exportListJson" style="margin-left: 8px;">导出列表</el-button>
    <span style="margin-left: 1000px;">
        <el-icon>
            <RefreshRight @click="adds" />
        </el-icon>
        &nbsp;
        <el-icon>
            <Setting @click="showa" v-model="counts" />
        </el-icon>
        &nbsp;
        <el-icon>
            <Filter @click="showwd" v-model="counte" />
        </el-icon>
    </span>

    <el-form :inline="true" :model="getdata" class="demo-form-inline" style="margin-top: 20px;" v-if="!showw">
        <el-form-item label="商品名称">
            <el-select v-model="getdata.shopName" clearable style="width: 200px;">
                <el-option v-for="item in Bind" :label="item.prodName" :value="item.prodId" />
            </el-select>
        </el-form-item>
        <el-form-item label="保质期">
            <el-input v-model="getdata.nums" clearable />
        </el-form-item>
        <el-form-item label="公司名称">
            <el-input v-model="getdata.Boss" clearable />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="GetTableData">查询</el-button>
        </el-form-item>
    </el-form>

    <el-table :data="tableData" border style="width: 100%;" @selection-change="handleSelectionChange"
        :row-key="getRowKey" v-show="!shows">
        <el-table-column type="selection" label="序号" width="55" />
        <el-table-column prop="prodName" label="商品名称" width="90" />
        <el-table-column prop="productuin" label="生产批次" width="90" />
        <el-table-column prop="dayNum" label="保质期(天)" width="90" />
        <el-table-column prop="productuinIcode" label="生产许可证号" width="140" />
        <el-table-column prop="enterprises" label="生产企业" width="130" />
        <el-table-column label="信息完整程度" width="160">
            <template #default="scope">
                <el-progress :percentage="scope.row.completePercent ?? calcRowPercent(scope.row)" :stroke-width="14"
                    :show-text="true" />
            </template>
        </el-table-column>
        <el-table-column prop="createName" label="创建人" width="90" />
        <el-table-column prop="createTime" label="创建时间" width="130">
            <template v-slot="scoped">
                {{ moment(scoped.row.createTime).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
        </el-table-column>
        <el-table-column prop="updateName" label="修改人" width="90" />
        <el-table-column prop="updateTime" label="修改时间" width="130">
            <template v-slot="scoped">
                {{ moment(scoped.row.updateTime).format("YYYY-MM-DD HH:mm:ss") }}
            </template>
        </el-table-column>
        <el-table-column label="操作" width="230">
            <template v-slot="scoped">
                <el-button link @click="DetailsQuery(scoped.row.productuin)" class="sas">
                    详情
                </el-button>

                <el-button link @click="ManageCreate(scoped.row)">
                    修改
                </el-button>

                <el-button link @click="exportBarcode(scoped.row)">
                    导出溯源码
                </el-button>

                <el-button link @click="DelManage(scoped.row.productId)">
                    删除
                </el-button>

            </template>
        </el-table-column>
    </el-table>


    <div class="demo-pagination-block" style="margin-top: 30px;" v-show="!shows">
        <el-pagination v-model:current-page="page.PageIndex" v-model:page-size="page.PageSize"
            :page-sizes="[2, 4, 6, 8, 10]" layout="total, sizes, prev, pager, next, jumper" :total="page.totalCount" />
    </div>
    <el-dialog v-model="dialogFormVisible" :title="model.title" width="800">
        <el-form :model="form" label-width="auto" style="max-width: 600px">

            <el-form-item label="商品名称">
                <el-select v-model="form.prodId" placeholder="商品名称">
                    <el-option v-for="item in Bind" :label="item.prodName" :value="item.prodId" />
                </el-select>
            </el-form-item>
            <el-form-item label="生产批次">
                <el-input v-model="form.productuin" />
            </el-form-item>
            <el-form-item label="保质期(天)">
                <el-input v-model="form.dayNum" />
            </el-form-item>
            <el-form-item label="生产许可证号">
                <el-input v-model="form.productuinIcode" />
            </el-form-item>
            <el-form-item label="生产企业">
                <el-input v-model="form.enterprises" />
            </el-form-item>
            <el-form-item label="封面图">
                <el-upload class="avatar-uploader" action="http://localhost:27167/api/Shops/ProduQueryImg"
                    :show-file-list="false" :on-success="handleAvatarSuccess">
                    <img v-if="form.coverImg" :src="form.coverImg" class="avatar" />
                    <el-icon v-else class="avatar-uploader-icon">
                        <Plus />
                    </el-icon>
                </el-upload>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="dialogFormVisible = false">重置</el-button>
                <el-button type="primary" v-if="model.isadd == true" @click="CreateManage(1)">
                    添加
                </el-button>
                <el-button type="primary" v-if="model.isadd == false" @click="CreateManage(a)">
                    修改
                </el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 溯源码一维码预览对话框 -->
    <el-dialog v-model="barcodeDialogVisible" title="溯源码预览" width="1250">
        <div style="text-align: center;">
            <canvas ref="barcodeCanvas"></canvas>
            <div style="margin-top: 8px; color: #666;">{{ barcodePreviewCode }}</div>
        </div>
    </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, watch, nextTick } from 'vue';
import axios from 'axios';
import moment from 'moment';
import { Traceab } from '@/Http/http'
import {
    RefreshRight,
    Plus,
    Setting,
    Filter
} from '@element-plus/icons-vue'
import { ElMessage, type UploadProps } from 'element-plus'
import { useRouter } from 'vue-router';
// 一维码生成与文件保存
import JsBarcode from 'jsbarcode'
import { saveAs } from 'file-saver'
const router = useRouter();
const tableData = ref<any>([])

const model = ref({
    isadd: false,
    title: "",
    ids: 0
})

const page = ref({
    PageIndex: 1,
    PageSize: 5,
    totalCount: 0,
    pageCount: 0
})
const showw = ref(false)
let counte = 0;
const showwd = () => {
    counte++;
    if (counte == 1) {
        showw.value = true
    }
    else if (counte == 2) {
        showw.value = false
        counte = 0;
    }
}

const shows = ref(false)
let counts = 0;
const showa = () => {
    counts++;
    if (counts == 1) {
        shows.value = true
    }
    else if (counts == 2) {
        shows.value = false
        counts = 0
    }


}

const getdata = ref<any>({

})
const GetTableData = () => {
    Traceab.get("/api/Shops/ProduQuert", {
        params: {
            PageIndex: page.value.PageIndex,
            PageSize: page.value.PageSize,
            totalCount: page.value.totalCount,
            pageCount: page.value.pageCount,
            shopName: getdata.value.shopName,
            nums: getdata.value.nums,
            Boss: getdata.value.Boss,
        }
    }).then(async res => {
        const rows = res.data.data.data || []
        // 初始化占位百分比，随后按详情模块更新
        tableData.value = rows.map((row: any) => ({
            ...row,
            completePercent: calcRowPercent(row)
        }))
        // 并行计算每条的详情模块完成度
        await computeAllRowsDetailCompletion()
        page.value.totalCount = res.data.data.totalCount;
        page.value.pageCount = res.data.data.pageCount;
        // 持久化到本地
        try {
            localStorage.setItem('management_table_data', JSON.stringify(tableData.value))
        } catch {}
    })
}

const adds = () => {
    GetTableData();
}
const a = ref([])
const dialogFormVisible = ref(false);
const ManageCreate = (row: any) => {
    if (row == null) {
        form.value.prodId = ""
        form.value.productuin = ""
        form.value.dayNum = ""
        form.value.productuinIcode = ""
        form.value.enterprises = ""
        form.value.coverImg = ""
        model.value.isadd = true
        model.value.title = "新增"
        dialogFormVisible.value = true
    }
    else {
        model.value.isadd = false
        model.value.title = "修改"
        model.value.ids = row.productId
        dialogFormVisible.value = true
        form.value.productId = row.productId
        form.value.prodId = row.prodId
        form.value.productuin = row.productuin
        form.value.dayNum = row.dayNum
        form.value.productuinIcode = row.productuinIcode
        form.value.enterprises = row.enterprises
        form.value.coverImg = row.coverImg
        a.value = row;
    }

}

const form = ref({
    "createName": " ",
    "productId": 0,
    "prodId": "",
    "productuin": "",
    "dayNum": "",
    "productuinIcode": "",
    "enterprises": "",
    "coverImg": ""
})


const Bind = ref([{
    "prodId": 0,
    "prodName": ""
}])

const GetBind = () => {
    form.value.createName = "张三"
    Traceab.get("/api/Shops/ProduciQuery").then(res => {
        Bind.value = res.data.data;
    })
}


const handleAvatarSuccess: UploadProps['onSuccess'] = (
    response,
    uploadFile
) => {
    form.value.coverImg = response
}

const CreateManage = (row: any) => {
    console.log(row)
    if (row == 1) {
        Traceab.post("/api/Shops/ShopsCreate", {
            data: form.value
        }).then(res => {
            if (res.data.code == 100) {
                ElMessage.success("新增成功")
                GetTableData();
            }
            else {
                ElMessage.error("新增失败")
            }
        })
    }
    else {
        console.log(row)
        form.value.createName = row.createName
        Traceab.put("/api/Shops/ProducUpdate", form.value).then(res => {
            if (res.data.code == 100) {
                ElMessage.success("修改成功")
                GetTableData();
            }
            else {
                ElMessage.error("修改失败")
            }
        })
    }

}

const arreryDel = ref<number[]>([])
const handleSelectionChange = (val: any[]) => {
    arreryDel.value = val.map((row: any) => row.productId)
}
const getRowKey = (row: any) => row.productId
// 依据已填写字段粗略估算完整度，可与详情模块规则对齐后替换
const calcRowPercent = (row: any) => {
    const checks = [
        !!row.prodName,
        !!row.productuin,
        !!row.dayNum,
        !!row.productuinIcode,
        !!row.enterprises,
        !!row.coverImg,
    ]
    const filled = checks.filter(Boolean).length
    return Math.round((filled / checks.length) * 100)
}

// 依据详情模块计算完成度
const computeAllRowsDetailCompletion = async () => {
    const tasks = tableData.value.map(async (row: any, index: number) => {
        const percent = await computeDetailCompletionByProductuin(row.productuin)
        // 保底使用字段估算，选用较高值
        const fallback = calcRowPercent(row)
        row.completePercent = Math.max(percent, fallback)
        console.log(row.completePercent)
        return row

    })
    await Promise.allSettled(tasks)
}

// 详情模块：按模块是否有数据计分
const computeDetailCompletionByProductuin = async (productuin: any) => {
    if (!productuin) return 0
    // 定义各模块查询；可按需增减或赋权重
    const moduleChecks = [
        // 屠宰信息
        Traceab.get('/api/Shops/SlantureQuery', { params: { Productuins: productuin } }).then(r => !!r?.data?.data).catch(() => false),
        // 屠宰企业
        Traceab.get('/api/Shops/BossQuery', { params: { Productuins: productuin } }).then(r => !!r?.data?.data).catch(() => false),
        // 加工班组
        Traceab.get('/api/Shops/OverTimeQuery', { params: { Productuins: productuin } }).then(r => !!r?.data?.data).catch(() => false),
        // 加工企业
        Traceab.get('/api/Shops/ProcssQuery', { params: { Productuins: productuin } }).then(r => !!r?.data?.data).catch(() => false),
        // 原料图片
        Traceab.get('/api/Shops/ImgQuery', { params: { name: '原料', Productuins: productuin } }).then(r => Array.isArray(r?.data?.data) && r.data.data.length > 0).catch(() => false),
        // 辅料图片
        Traceab.get('/api/Shops/ImgQuery', { params: { name: '辅料', Productuins: productuin } }).then(r => Array.isArray(r?.data?.data) && r.data.data.length > 0).catch(() => false),
        // 添加剂图片
        Traceab.get('/api/Shops/ImgQuery', { params: { name: '添加剂', Productuins: productuin } }).then(r => Array.isArray(r?.data?.data) && r.data.data.length > 0).catch(() => false),
        // 包材图片
        Traceab.get('/api/Shops/ImgQuery', { params: { name: '包材', Productuins: productuin } }).then(r => Array.isArray(r?.data?.data) && r.data.data.length > 0).catch(() => false),
        // 企业图片
        Traceab.get('/api/Shops/ImgQuery', { params: { name: '企业图片', Productuins: productuin } }).then(r => Array.isArray(r?.data?.data) && r.data.data.length > 0).catch(() => false),
    ]

    const results = await Promise.allSettled(moduleChecks)
    const bools = results.map(r => (r.status === 'fulfilled' ? (r as any).value === true : false))
    const filled = bools.filter(Boolean).length
    const percent = Math.round((filled / bools.length) * 100)
    return percent
}
//删除（支持单个或批量）
const DelManage = (input: any) => {
    // input 可能是单个主键或选中行数组
    const ids: number[] = Array.isArray(input)
        ? input.map((row: any) => (typeof row === 'object' ? row.productId : row))
        : (Array.isArray(arreryDel.value) && arreryDel.value.length > 0
            ? arreryDel.value
            : [input])

    if (!ids || ids.length === 0 || ids[0] == null) {
        ElMessage.error("请选择要删除的数据")
        return
    }

    Traceab.delete("/api/Shops/ProduciDel", {
        params: {
            Id: ids.join(',')
        }
    }).then(res => {
        if (res.data.code == 100) {
            ElMessage.success("删除成功")
            GetTableData()
        }
        else {
            ElMessage.error("删除失败")
        }
    })
}


const DetailsQuery = (productuin: any) => {
    router.push({
        path: "/cultivation", query: {
            productuin: productuin
        }
    })
}

onMounted(() => {
    // 先尝试加载本地缓存
    try {
        const cached = localStorage.getItem('management_table_data')
        if (cached) {
            const parsed = JSON.parse(cached)
            if (Array.isArray(parsed)) {
                tableData.value = parsed
            }
        }
    } catch {}
    GetTableData();
    GetBind();
})

watch(page.value, () => {
    GetTableData()
})

// 导出当前行的一维码(Code128)，基于 production 批次号
const exportBarcode = (row: any) => {
    const code = row?.productuin || row?.prodName || ''
    if (!code) {
        ElMessage.error('无有效溯源码内容')
        return
    }
    barcodePreviewCode.value = String(code)
    barcodeDialogVisible.value = true
    nextTick(() => {
        try {
            if (!barcodeCanvas.value) return
            // 将条码内容设置为可直接打开详情页的地址，扫码即可查看当前行数据
            const resolved = router.resolve({ path: '/cultivation', query: { productuin: barcodePreviewCode.value } })
            const scanContent = window.location.origin + resolved.href
            JsBarcode(barcodeCanvas.value, scanContent, {
                format: 'CODE128',
                displayValue: true,
                background: '#ffffff',
                lineColor: '#000000',
                width: 2,
                height: 80,
                fontSize: 14,
                margin: 10,
                // 显示产品批次文本，避免展示长链接
                text: barcodePreviewCode.value,
                textMargin: 6
            })
        } catch (e) {
            ElMessage.error('条码生成失败')
        }
    })
}

// 导出表格数据为 JSON 文件
const exportListJson = () => {
    try {
        const json = JSON.stringify(tableData.value, null, 2)
        const blob = new Blob([json], { type: 'application/json;charset=utf-8' })
        const ts = moment().format('YYYYMMDD_HHmmss')
        saveAs(blob, `management_list_${ts}.json`)
    } catch {
        ElMessage.error('导出列表失败')
    }
}

// 一维码预览对话框状态与画布引用
const barcodeDialogVisible = ref(false)
const barcodePreviewCode = ref('')
const barcodeCanvas = ref<HTMLCanvasElement | null>(null)
</script>

<style scoped>
.avatar-uploader .avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}


.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>